import React from 'react';
import { Card, Button, Table, Space, Modal, TableProps, message, Cascader } from 'antd';
import { useParams } from 'react-router-dom';
import _ from 'lodash';
import { type FormPanelObject, InputType } from 'lfun-bg-comp';
import utils from '@/utils';
import FormPanelWrapper from '../../component/FormPanelWrapper';
import { TeaDomesticTrainingSrv } from '@/service/teacher';
import { TRAINING_MODE, TRAINING_TYPE, TRAINING_YEAR } from '@/constant/teachOptions';
import { isPermissionOperate } from '@/component/permission-button';

const DomesticTraining: React.FC<{ isEditPanel?: boolean }> = ({ isEditPanel = true }) => {
  const columns: TableProps['columns'] = [
    {
      title: '培训年度',
      dataIndex: 'training_year',
      key: 'training_year',
      // render: (text: any) => {
      //   if (!text) return '';
      //   text = _.isArray(text) ? text : text.split(',');
      //   const arr: any[] = text.map(v => utils.findLabelDeep(TRAINING_YEAR, String(v)));
      //   return arr.join('-');
      // },
    },
    {
      title: '培训类别',
      dataIndex: 'training_type',
      key: 'training_type',
      render: (text: any) => {
        if (!text) return '';
        text = _.isArray(text) ? text : text.split(',');
        const arr: any[] = text.map(v => utils.findLabelDeep(TRAINING_TYPE, String(v)));
        return arr.join('-');
      },
    },
    {
      title: '培训项目名称',
      dataIndex: 'training_project',
      key: 'training_project',
    },
    {
      title: '培训机构名称',
      dataIndex: 'training_institution',
      key: 'training_institution',
    },
    {
      title: '培训方式',
      dataIndex: 'training_mode',
      key: 'training_mode',
      render: (text: any) => {
        if (!text) return '';
        text = _.isArray(text) ? text : text.split(',');
        const arr: any[] = text.map(v => utils.findLabelDeep(TRAINING_MODE, String(v)));
        return arr.join('-');
      },
    },
    {
      title: '培训获得学时',
      dataIndex: 'training_hours',
      key: 'training_hours',
    },
    {
      title: '培训获得学分',
      dataIndex: 'training_credits',
      key: 'training_credits',
    },
    {
      title: '操作',
      key: 'actions',
      //width: 200,
      fixed: 'right',
      align: 'center',
      hidden: !isPermissionOperate(),
      render: (text, record) => (
        <Space>
          {isEditPanel && (
            <Button type="link" onClick={() => handleEdit(record)}>
              编辑
            </Button>
          )}
          {isEditPanel && (
            <Button type="link" onClick={() => handleDelete(record)}>
              删除
            </Button>
          )}
          {!isEditPanel && (
            <Button type="link" onClick={() => handleEdit(record)}>
              查看
            </Button>
          )}
        </Space>
      ),
    },
  ];

  const list = [
    {
      title: '',
      labelCol: { span: 8 },
      wrapperCol: { span: 16 },
      span: 12,
      inputs: [
        {
          label: '培训年度',
          name: 'training_year',
          key: 'training_year',
          required: true,
          inputType: InputType.select,
          //renderOption: TRAINING_YEAR,
          renderOption: () => {
            const year = new Date().getFullYear();
            const options = [];
            for (let i = 0; i < 60; i++) {
              options.push({
                label: `${year - i}`,
                value: `${year - i}`,
              });
            }
            return options;
          },
        },
        {
          label: '培训类别',
          name: 'training_type',
          key: 'training_type',
          required: true,
          inputType: InputType.select,
          renderOption: TRAINING_TYPE,
        },
        {
          label: '培训项目名称',
          name: 'training_project',
          key: 'training_project',
          required: true,
          textRange: [0, 20],
        },
        {
          label: '培训机构名称',
          name: 'training_institution',
          key: 'training_institution',
          textRange: [0, 20],
        },
        {
          label: '培训方式',
          name: 'training_mode',
          key: 'training_mode',
          required: true,
          inputType: InputType.select,
          renderOption: TRAINING_MODE,
        },
        {
          label: '培训获得学时',
          name: 'training_hours',
          key: 'training_hours',
          required: true,
          textRange: [0, 20],
        },
        {
          label: '培训获得学分',
          name: 'training_credits',
          key: 'training_credits',
          textRange: [0, 20],
        },
      ],
    },
  ];

  const { id: teacher_id } = useParams();

  const [formValue, setFormValue] = React.useState({});
  const [dataSource, setDataSource] = React.useState([]);
  const [currentRowId, setCurrentRowId] = React.useState(null);

  React.useEffect(() => {
    fetchData();
  }, []);

  const fetchData = async () => {
    const res = await TeaDomesticTrainingSrv.list({ teacher_id });
    console.log('🚀 ~ fetchData ~ res:', res);
    if (res.success) {
      setDataSource(res.data);
    }
  };
  // 新增 | 编辑
  const [showFormModel, setFormModel] = React.useState(false);
  const [isEdit, setIsEdit] = React.useState(false);

  const handleAdd = () => {
    setIsEdit(false);
    setFormValue({});
    setFormModel(true);
  };

  const handleEdit = async (record: any) => {
    const { data } = await TeaDomesticTrainingSrv.detail(record.domestic_training_id);

    const params = {
      ...data,
      //training_year: data.training_year ? data.training_year?.split(',') : [],
      //training_type: data.training_type ? data.training_type?.split(',') : [],
      //training_mode: data.training_mode ? data.training_mode?.split(',') : [],
    };
    setCurrentRowId(record.domestic_training_id);

    setFormValue(params);
    setIsEdit(true);
    setFormModel(true);
  };

  const handleDelete = (record: any) => {
    // content 按最字段内容为准，格式是否删除${证件类型}:${证件号码},姓名${姓名}的教师信息?
    Modal.confirm({
      title: '删除',
      content: `是否删除培训年度: ${record.training_year} 相关信息?`,
      onOk: async () => {
        console.log('OK');
        const res = await TeaDomesticTrainingSrv.delete(record.domestic_training_id);
        if (res.success) {
          message.success('删除成功');
          fetchData();
        }
      },
    });
  };

  const handleSave = async (formPanelObject: FormPanelObject) => {
    const values = formPanelObject.getFieldsValue();
    console.log('🚀 ~ handleSave ~ values:', values);
    const params = {
      ...values,
      teacher_id,
    };

    //params.training_year = params.training_year?.join(',');
    //params.training_type = params.training_type?.join(',');
    //params.training_mode = params.training_mode?.join(',');

    if (isEdit) {
      params.domestic_training_id = currentRowId;
    }

    // 新增 | 编辑
    const server = isEdit ? 'update' : 'add';
    const res = await TeaDomesticTrainingSrv[server](params);
    if (res.success) {
      message.success('保存成功');
      formPanelObject.resetFields();
      setFormModel(false);
      fetchData();
      setCurrentRowId(null);
    } else {
      formPanelObject.reVaildation(res);
    }
  };

  return (
    <Card title="国内培训" bordered={false}>
      {isEditPanel && (
        <Button type="primary" style={{ marginBottom: '20px' }} onClick={handleAdd}>
          新增
        </Button>
      )}
      <Table dataSource={dataSource} columns={columns} scroll={{ x: 'max-content' }} />
      <FormPanelWrapper
        title={isEdit ? (isEditPanel ? '国内培训编辑' : '国内培训详情') : '国内培训新增'}
        visible={showFormModel}
        formValue={formValue}
        changeValue={setFormValue}
        formList={list}
        onCancel={() => setFormModel(false)}
        onSave={handleSave}
        isEdit={isEditPanel}
      />
    </Card>
  );
};

DomesticTraining.defaultProps = {
  isEditPanel: true,
};

export default DomesticTraining;
